<template>
  <div id="draw-panel">
    <iframe
      src="https://embed.diagrams.net?embed=1&lang=zh&ui=atlas&spin=1&noSaveBtn=1&modified=unsavedChanges&proto=json&configure=1"
      frameborder="0"
      ref="drawIframeRef"
    >
    </iframe>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'

const props = defineProps({
  dataSrc: String,
})

const drawIframeRef = ref()

const emits = defineEmits(['closeHandle'])

const reFn = (e) => {
  try {
    if (e.data && JSON.parse(e.data)) {
      const data = JSON.parse(e.data)
      if (data.event == 'configure') {
        drawIframeRef.value.contentWindow.postMessage(
          JSON.stringify({
            action: 'configure',
          }),
          '*',
        )
      } else if (data.event == 'init') {
        // 如果编辑器已经加载完成，则初始化
        drawIframeRef.value.contentWindow.postMessage(
          JSON.stringify({
            action: 'load',
            xmlpng: props.dataSrc,
          }),
          '*',
        )
      } else if (data.event == 'exit') {
        emits('closeHandle')
      } else if (data.event == 'save') {
        drawIframeRef.value.contentWindow.postMessage(
          JSON.stringify({
            action: 'export',
            format: 'xmlpng',
            spinKey: 'saving',
          }),
          '*',
        )
      } else if (data.event == 'export') {
        emits('closeHandle', data.data)
      }
    }
  } catch (err) {
    console.log('err', err)
  }
}

onMounted(() => {
  window.addEventListener('message', reFn)
})
onBeforeUnmount(() => {
  window.removeEventListener('message', reFn)
})
</script>

<style lang="scss" scoped>
#draw-panel {
  position: relative;
  top: 0;
  left: 0;
  height: 100%;
  iframe {
    width: 100% !important;
    height: 100% !important;
  }
}
</style>
